package com.pan.admin.module.crm.controller;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Empty;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.StringUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pan.admin.common.annotation.Log;
import com.pan.admin.common.core.controller.BaseController;
import com.pan.admin.common.core.domain.AjaxResult;
import com.pan.admin.common.core.page.TableDataInfo;
import com.pan.admin.common.enums.BusinessType;
import com.pan.admin.common.utils.PageUtils;
import com.pan.admin.common.utils.SecurityUtils;
import com.pan.admin.module.crm.entity.po.CrmLoanUserDistributeStatusPO;
import com.pan.admin.module.crm.entity.qo.CrmLoanUserDistributeStatusQO;
import com.pan.admin.module.crm.entity.vo.CrmAddVo;
import com.pan.admin.module.crm.entity.vo.CrmDistributeLoanUserVO;
import com.pan.admin.module.crm.entity.vo.TreeListVo;
import com.pan.admin.module.crm.service.CrmDistributeService;
import com.pan.admin.module.loanUser.entity.LoanUserRegister;
import com.pan.admin.module.loanUser.entity.po.LoanUserFormFieldPO;
import com.pan.admin.module.loanUser.entity.po.LoanUserRegisterTracePO;
import com.pan.admin.module.loanUser.service.LoanUserFormFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;


/**
 * 甲方与用户关联Controller
 *
 * @author ts
 * @date 2023-11-13
 */
@RestController
@RequestMapping("/crm/jf/user")
public class CrmLoanUserController extends BaseController {

    @Autowired
    private CrmDistributeService distributeLoanUserService;
    @Autowired
    private LoanUserFormFieldService loanUserFormFieldService;

    /**
     * 查询甲方与用户关联列表
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:list')")
    @GetMapping("/list")
    public TableDataInfo list(CrmDistributeLoanUserVO crmLoanUser) {
        Integer productId = SecurityUtils.getLoginUser().getUser().getProductId();
        Assert.isNotNull(productId);

        //  设置分配状态
        PageUtils.startPage();
        // 分页不执行count语句查询总行数
        PageHelper.getLocalPage().count(false);
        List<LoanUserRegister> list = distributeLoanUserService.list(crmLoanUser);
        if (ValidParam.isEmpty(list)) {
            return getDataTable(Empty.list());
        }
        PageInfo<LoanUserRegister> pageInfo = new PageInfo<>(list);


        //  返回list
        List<CrmDistributeLoanUserVO> resultList = CopyUtils.copyList(list, CrmDistributeLoanUserVO.class);
        List<Long> loanUserIds = CollUtils.toList(resultList, t -> t.getId());

        //  查询分配状态
        CrmLoanUserDistributeStatusQO crmLoanUserDistributeStatusQO = new CrmLoanUserDistributeStatusQO();
        crmLoanUserDistributeStatusQO.setLoanUserIds(loanUserIds);
        crmLoanUserDistributeStatusQO.setProductId(productId);
        List<CrmLoanUserDistributeStatusPO> listDistributeStatus = distributeLoanUserService.listUserDistributeStatus(crmLoanUserDistributeStatusQO);

        //  设置分配状态
        IteratorUtils.array(resultList, t -> {
            //  默认分配状态
            t.setDistributeStatus(0);

            List<CrmLoanUserDistributeStatusPO> listCrmUser = CollUtils.find(listDistributeStatus, t2 -> Eq.object(t.getId(), t2.getLoanUserId()));

            StringBuilder distributeUserNameBuild = StringUtils.createBuilder();
            IteratorUtils.array(listCrmUser, t2 -> {
                //  分配状态
                t.setDistributeStatus(1);
                //  分配用户名
                if (distributeUserNameBuild.length() > 0) {
                    distributeUserNameBuild.append("/");
                }
                distributeUserNameBuild.append(t2.getNickName());
            });
            t.setDistributeUserName(distributeUserNameBuild.toString());
        });
        return getDataTable(resultList, pageInfo.getTotal());
    }

    /**
     * 左树节点渲染
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:distribute')")
    @GetMapping("/treeList")
    public AjaxResult treeList(CrmDistributeLoanUserVO crmLoanUser) {
        TreeListVo listVo = distributeLoanUserService.treeLeftList(crmLoanUser);
        return AjaxResult.success(listVo);
    }

    /**
     * 左树节点渲染(子节点点击)
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:distribute')")
    @GetMapping("/treeListChildren")
    public AjaxResult treeListChildren(CrmDistributeLoanUserVO crmLoanUser) {
        TreeListVo listVo = distributeLoanUserService.treeListChildren(crmLoanUser);
        return AjaxResult.success(listVo);
    }

    /**
     * 左边父级节点点击渲染
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:distribute')")
    @GetMapping("/treeRightList")
    public AjaxResult treeRightList(CrmDistributeLoanUserVO crmLoanUser) {
//        crmLoanUser.getDeptId();
//        TreeListVo listVo = distributeLoanUserService.treeList(crmLoanUser);
//        return AjaxResult.success(listVo);
        return AjaxResult.success();
    }

    /**
     * 甲方公海用户分配
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:distribute')")
    @Log(title = "CRM公海分配", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrmAddVo crmAddVo) {
        return toAjax(distributeLoanUserService.insertLoanJfUser(crmAddVo));
    }

//    /**
//     * 获取甲方与用户关联详细信息
//     */
//    @PreAuthorize("@ss.hasPermi('crm:jf:user:query')")
//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id) {
//        return success(distributeLoanUserService.getById(id));
//    }

    /**
     * 获取用户注册详细信息
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:list')")
    @GetMapping(value = "/getByLoanUserId")
    public AjaxResult getUserInfo(CrmDistributeLoanUserVO crmDistributeLoanUserVO) {
        Integer productId = SecurityUtils.getLoginUser().getUser().getProductId();
        Assert.isNotNull(productId);
        //  需要做数据权限处理
        Integer loanUserId = crmDistributeLoanUserVO.getLoanUserId();
        if (loanUserId == null) {
            return error("非法id");
        }

        CrmDistributeLoanUserVO byId = distributeLoanUserService.getByLoanUserId(crmDistributeLoanUserVO);
        if (byId == null) {
            return error("非法获取数据");
        }
        return success(byId);
    }

    /**
     * 获取相关联用户资质
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:field')")
    @GetMapping("/getUserField")
    public AjaxResult getUserField(CrmDistributeLoanUserVO crmDistributeLoanUserVO) {
        Integer productId = SecurityUtils.getLoginUser().getUser().getProductId();
        Assert.isNotNull(productId);
        // 防止越权
        Integer id = crmDistributeLoanUserVO.getLoanUserId();
        if (id == null) {
            return error("非法获取");
        }
        CrmDistributeLoanUserVO byId = distributeLoanUserService.getByLoanUserId(crmDistributeLoanUserVO);
        if (byId == null) {
            return error("非法获取2");
        }
        //  获取用户关联资质
        List<LoanUserFormFieldPO> userFormField = loanUserFormFieldService.getUserFormField(id);
        return success(userFormField);
    }

    /**
     *  用户评级
     *
     *  @param crmDistributeLoanUserVO
     *  @return AjaxResult
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:rating')")
    @PostMapping("/update/userRating")
    public AjaxResult updateUserRating(@RequestBody CrmDistributeLoanUserVO crmDistributeLoanUserVO) {
        Integer productId = SecurityUtils.getLoginUser().getUser().getProductId();
        Assert.isNotNull(productId);
        // 防止越权
        Long id = crmDistributeLoanUserVO.getId();
        if (id == null) {
            return error("非法更新");
        }

        crmDistributeLoanUserVO.setLoanUserId(id.intValue());
        CrmDistributeLoanUserVO byId = distributeLoanUserService.getByLoanUserId(crmDistributeLoanUserVO);
        if (byId == null) {
            return error("非法更新2");
        }

        LoanUserRegisterTracePO loanUserRegisterTrace = new LoanUserRegisterTracePO();
        loanUserRegisterTrace.setLoanUserRegisterId(id);
        loanUserRegisterTrace.setLoanProductId(productId);
        loanUserRegisterTrace.setRating(crmDistributeLoanUserVO.getRating());
        loanUserRegisterTrace.setRemark(crmDistributeLoanUserVO.getRemark());
        loanUserRegisterTrace.setTraceStatus(crmDistributeLoanUserVO.getTraceStatus());
        loanUserRegisterTrace.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        loanUserRegisterTrace.setUpdateTime(new Date());
        return success(this.distributeLoanUserService.updateLoanUserRegisterTrace(loanUserRegisterTrace));
    }
}
